package org.chinasoft.aspect;

import org.apache.shiro.authc.IncorrectCredentialsException;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.chinasoft.exceptions.CheckException;
import org.chinasoft.utils.ResultBean;
import org.springframework.stereotype.Component;

@Component
@Aspect
public class ControllerExceptionAop {
    @Pointcut("@annotation(org.chinasoft.aspect.ExceptionHandler)")
    public void pointcut() {
    }

    @Around("pointcut()")
    public Object handlerControllerMethod(ProceedingJoinPoint pjp) {
        ResultBean<?> resultBean;
        try {
            resultBean = (ResultBean<?>) pjp.proceed();
        } catch (Throwable e) {
            resultBean = handlerException(e);
        }
        return resultBean;
    }

    private ResultBean<?> handlerException(Throwable e) {
        ResultBean<?> resultBean = new ResultBean<>();
        if (e instanceof CheckException) {
            // 校验异常
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setInfo(e.getMessage());
        } else if (e instanceof IncorrectCredentialsException) {
            // 校验异常
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setInfo("用户名或密码错误!");
        } else {
            // 未知异常
            resultBean.setCode(ResultBean.FAIL);
            resultBean.setInfo(e.getMessage());
        }
        return resultBean;
    }
}
